package com.caltco.cargo.ops.auth.component;

import cn.hutool.json.JSONUtil;
import com.caltco.cargo.ops.common.api.CommonResult;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

/**
 * @program: agilefast-framework
 * @description: 自定义返回结果：未登录或登录过期
 * @author: yehao
 * @create: 2022-07-20 13:41
 **/
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Value("${multimodule.open}")
    private Boolean isModule;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        if(!isModule){
            response.setHeader("Access-Control-Allow-Origin","*");
        }
        response.setHeader("Cache-Control","no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSONUtil.parse(CommonResult.unauthorized(authException.getMessage())));
        response.getWriter().flush();
    }
}
